#include "serialchoosedialog.h"
#include "ui_serialchoosedialog.h"
#include "src/globalvar.h"
#include "src/serialcontroller.h"
#include <QStringList>
#include "src/qserialproto.h"

SerialChooseDialog::SerialChooseDialog(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::SerialChooseDialog)
{
    ui->setupUi(this);
    SerialController *controller = new SerialController;
    auto ports = controller->GetPorts();

    for(uint32_t i = 0;i < ports.length();i++){
        ui->comboBox->addItem(ports.at(i).portName());
    }
    QStringList list;
    list<<"1200"<<"2400"<<"4800"<<"9600"<<"19200"<<"38400"
       <<"57600"<<"115200"<<"128000"<<"256000";
    ui->comboBox_2->addItems(list);
}

SerialChooseDialog::~SerialChooseDialog()
{
    delete ui;
}

void SerialChooseDialog::on_pushButton_clicked()
{
    if(ui->pushButton->text() == "打开"){
        auto port = ui->comboBox->itemText(ui->comboBox->currentIndex());
        auto baudrate =  ui->comboBox_2->itemText(ui->comboBox_2->currentIndex());
        SerialController *controller = new SerialController;
        controller->SetProto(&GlobalVarManager::Instance()->SerialProto());
        if (OK == controller->OpenSerial(port,"115200","8","1","none")){
            ui->pushButton->setText("关闭");
        }
        GlobalVarManager::Instance()->SetSerialController(controller);
    }else{
        GlobalVarManager::Instance()->GetSerailController()->CloseSerial();
        ui->pushButton->setText("打开");
    }
}
